package com.wedimob.slideshare.task.io.disk;

import java.net.URI;
import java.text.DecimalFormat;

import com.wedimob.slideshare.RuntimeConfig;
import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.bo.SharedDocument;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;

public class TaskDocumentWriter extends Task<SharedDocument, SharedDocument> {

    private WriteType write;

    public TaskDocumentWriter(PoolExecutor pool, SharedDocument input, WriteType write, int timeout) {
        super(pool, input, 0, timeout);
        this.write = write;
    }

    @Override
    public void run() {
        try {
            URI uri = PathHelper.buildTmpFile("index.html", input.getSummary().getAuthor(), input.getSummary().getTitle());
            
            System.err.println("TaskDocumentWriter uri{" + uri + "} start");
            
            
            StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            sb.append("<body>");
            sb.append("<div>");
            sb.append("<a href='");
            sb.append(input.getSummary().getUrl());
            sb.append("'>");
            sb.append(input.getSummary().getTitle());
            sb.append("</a>");
            sb.append("</div>");
            DecimalFormat decFormat = new DecimalFormat("0000");
            for (int i = 1; i < input.getMedia().size(); i++) {
                String imgPath = decFormat.format(i) + ".jpeg";
                sb.append("<br/><img src='");
                sb.append(imgPath);
                sb.append("'/>");
            }
            sb.append("</body>");
            sb.append("</html>");

            RuntimeConfig.getInstance().getWriter().write(sb.toString().getBytes(), uri);

            if (write != WriteType.NONE)
                pool.execAsync(new TaskDocumentCBRWriter(pool, input, timeout));
            
            System.err.println("TaskDocumentWriter uri{" + uri + "} end");

        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }
}
